const fs = require("fs")
const path = require("path")
const child_process = require("child_process")

// 预打包脚本
function deleteFolderRecursive(url) {
  var files = [];
  /**
   * 判断给定的路径是否存在
   */
  if (fs.existsSync(url)) {
    /**
     * 返回文件和子目录的数组
     */
    files = fs.readdirSync(url);
    files.forEach(function (file, index) {

      var curPath = path.join(url, file);
      /**
       * fs.statSync同步读取文件夹文件，如果是文件夹，在重复触发函数
       */
      if (fs.statSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);

      } else {
        fs.unlinkSync(curPath);
      }
    });
    /**
     * 清除文件夹
     */
    fs.rmdirSync(url);
  } else {
    console.log("给定的路径不存在，请给出正确的路径");
  }
}

async function childSpawnPromise(command, args) {
  return new Promise((resolve,reject)=>{
    const cmd = child_process.spawn(command, args, { shell: true})
    let datas = ''
    // 为了解决类型问题
    cmd.stdout.on('data', (data) => {
      datas += data
    });

    cmd.on('error', (data) => {
      reject(`执行命令发生错误:err:${data}, command:${command}`)
    });

    cmd.on('exit',(code, err)=>{
      resolve(datas)
    })
  })
}

const cmd = `git rev-list --all --count`



async function main() {
  console.log("开始执行预编译脚本")
  let title = `Chessmate V`
  let packageJson = fs.readFileSync('./package.json')
  packageJson = JSON.parse(packageJson)
  let version = packageJson.version
  title += version


  const res = await childSpawnPromise(cmd)
  title+=`.${res}`
  let htmlData = `
  <!DOCTYPE html>
    <html lang="">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <link rel="icon" href="<%= BASE_URL %>chessmate.ico">
        <title> ${title} </title>
      </head>
      <body>
        <noscript>
          <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
        </noscript>
        <div id="app"></div>
        <!-- built files will be auto injected -->
      </body>
  </html>`

  console.log("写入html版本号")
  fs.writeFileSync('./public/index.html', htmlData)
  fs.writeFileSync('./db/version.txt', title)
  console.log("写入版本号文件")
  deleteFolderRecursive('./dist_electron')
  console.log("清空dist_electron文件夹")
}


main()